package com.momoauth.api_client.controller;

import com.momoauth.api_client.entity.User;
import com.momoauth.api_client.mapper.UserMapper;
import com.momoauth.api_client.utils.SecurityUtils;
import com.momoauth.common.core.result.ResponseResurt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/mine")
@Api(tags = "我的")
public class MineController {

    @Resource
    UserMapper userMapper;

    @Resource
    SecurityUtils securityUtils;

    /**
     * 修改密码
     * @param user
     * @param request
     * @return
     */
    @ApiOperation(value = "修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "password", value = "密码", required = true)
    })
    @RequestMapping(value = "/changePassword", method = RequestMethod.POST)
    public ResponseResurt changePassword(User user, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Long userId = Long.parseLong(securityUtils.getClaimName(token,"userId"));
        user.setUserId(userId); //用户ID
        String password = user.getPassword();
        String salt = userMapper.selectById(user.getUserId()).getSalt();
        user.setPassword(securityUtils.getMD5Pwd(password,salt)); //重新加密的密码
        //执行更新操作
        int isUpdate = userMapper.changePassword(user);
        if (isUpdate > 0) {
            return ResponseResurt.success().msg("恭喜您，修改成功。");
        }
        return ResponseResurt.error().msg("很抱歉，修改失败！");
    }
}
